const Router = require('koa-router')
const { error, INFO } = require('./utils/error')
const {
  requestContributed,
  requestReturned,
  requestReview
} = require('./api/contribution')
const apiError = (info) => {
  error('50000', __filename, info)
}
const router = new Router({
  prefix: '/api/contribution'
})
router.get('/contributed', async (ctx) => {
  const { page, limit } = ctx.query
  let result
  let code = -1
  let msg = ''
  let len = 0
  try {
    const { status, data } = await requestContributed({
      id: ctx.session.passport.user.id,
      curr: page,
      limit
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      len = +data.msg
      result = data.data
        .filter((_, index) => {
          return index + 1 <= limit
        })
        .map((item) => {
          return {
            id: item.id,
            title: item.title,
            browse: item.browse,
            comments: item.comments,
            time: item.date
          }
        })
    }
  } catch (error) {
    apiError('GET-contributed')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      len,
      data: result,
      msg
    }
  }
})
router.get('/review', async (ctx) => {
  const { page, limit } = ctx.query
  let result
  let code = -1
  let msg = ''
  let len = 0
  try {
    const { status, data } = await requestReview({
      id: ctx.session.passport.user.id,
      curr: page,
      limit
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      len = +data.msg
      result = data.data
        .filter((_, index) => {
          return index + 1 <= limit
        })
        .map((item) => {
          return {
            id: item.id,
            title: item.title,
            time: item.date
          }
        })
    }
  } catch (error) {
    apiError('GET-review')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      len,
      data: result,
      msg
    }
  }
})
router.get('/returned', async (ctx) => {
  const { page, limit } = ctx.query
  let result
  let code = -1
  let msg = ''
  let len = 0
  try {
    const { status, data } = await requestReturned({
      id: ctx.session.passport.user.id,
      curr: page,
      limit
    })
    if (status === 200 && data.statu === 0) {
      code = 1
      len = +data.msg
      result = data.data
        .filter((_, index) => {
          return index + 1 <= limit
        })
        .map((item) => {
          return {
            id: item.id,
            title: item.title,
            time: item.pullDate,
            reason: item.content
          }
        })
    }
  } catch (error) {
    apiError('GET-returned')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      len,
      data: result,
      msg
    }
  }
})
module.exports = router
